package com.weisy.signin.network.resource;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.weisy.signin.bean.MsgEvent;
import com.weisy.signin.bean.Sign;
import com.weisy.signin.bean.Student;
import com.weisy.signin.bean.Teacher;
import com.weisy.signin.comm.Comm;
import com.weisy.signin.network.utils.HttpContext;
import com.weisy.signin.network.utils.StreamToolkit;
import com.weisy.signin.utils.GsonUtils;
import com.weisy.signin.utils.Logs;
import com.weisy.signin.utils.SpUtils;
import com.weisy.signin.utils.TimeUtils;

import org.greenrobot.eventbus.EventBus;
import org.litepal.LitePal;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.List;

import kotlin.text.Charsets;

/**
 * @author weisy
 * @function
 * @date 2019/3/22 21:54
 */
public class SignResourceUriHandler implements IResourceUriHandler {
    private String TAG = "SignResourceUriHandler";
    private String suffix = "/";
    private Context context;
    private Teacher teacher;

    public SignResourceUriHandler(Context context) {
        this.context = context;
        teacher = GsonUtils.str2Bean((String) SpUtils.get(context, Comm.SP_PERION, ""), Teacher.class);
    }

    @Override
    public boolean accept(String uri) {
        return uri.equals(suffix);
    }

    @Override
    public void handle(String uri, HttpContext httpContext) {
        Log.d(TAG, "uri=" + uri);
        String assetsPath = uri.substring(suffix.length());
        try {
            InputStream ins = httpContext.underlySocket.getInputStream();
            String readLine;
            while ((readLine = StreamToolkit.readContent(ins)) != null) {
                if (TextUtils.isEmpty(readLine)) {
                    break;
                }
                Logs.d(TAG, "data=" + readLine);
                Student student = GsonUtils.str2Bean(readLine, Student.class);
                List<Student> students = LitePal.where("studentId=?", student.getStudentId()).find(Student.class);
                if (students.size() == 0) {
                    student.save();
                } else {
                    student.setScore(students.get(0).getScore());
                    student.setMidScore(students.get(0).getMidScore());
                    student.setEndScore(students.get(0).getEndScore());
                    student.updateAll("studentId=?", student.getStudentId());
                }
                //同一用户是否已经签过到
                boolean isSign = false;
                //签到失败原因
                String msg = "";

                //判断同一用户是否已签到
                List<Sign> signs = LitePal.where("studentId=?", student.getStudentId()).find(Sign.class);
                Logs.d(TAG, "SIGNS:" + signs.toString());
                for (Sign sign : signs) {
                    Logs.d(TAG, "上次签到时间差：" + TimeUtils.compareTime(sign.getSignTime()));
                    if (TimeUtils.compareTime(sign.getSignTime()) < 45 * 60) {
                        msg = "您已经签过到，请不要重复签到";
                        isSign = true;
                        break;
                    }
                }
                //判断是否同一设备多个用户签到
                List<Sign> signs1 = LitePal.where("device=?", student.getDevice()).find(Sign.class);
                for (Sign sign : signs1) {
                    if (TimeUtils.compareTime(sign.getSignTime()) < 45 * 60 && !sign.getStudentId().equals(student.getStudentId())) {
                        msg = "请不要代替他人签到";
                        isSign = true;
                        break;
                    }
                }

                Sign sign = new Sign();
                sign.setStudentId(student.getStudentId());
                if (!isSign) {
                    sign.setSignCourse(teacher.getCourse());
                    sign.setSignTime(TimeUtils.getCurrent());
                    sign.setPhone(student.getPhone());
                    sign.setName(student.getName());
                    sign.setDevice(student.getDevice());
                    sign.setImgUrl(student.getImgUrl());
                    sign.save();
                    EventBus.getDefault().post(new MsgEvent(Comm.SIGN_INFO, sign));
                }
                String response = GsonUtils.bean2Str(new MsgEvent(Comm.SIGN_RESULT, msg, GsonUtils.bean2Str(sign)));
                Log.i(TAG, "响应消息：");
                OutputStreamWriter osw = new OutputStreamWriter(httpContext.underlySocket.getOutputStream(), Charsets.UTF_8);
                StringBuilder sb = new StringBuilder();
                sb.append("HTTP/1.1 200 OK\r\n");
                sb.append("Connection: keep-alive\r\n");
                sb.append("Content-length: ").append(response.length()).append("\r\n");
                sb.append(StreamToolkit.addContentType(assetsPath)).append("\r\n");
                sb.append("\r\n");
                sb.append(response).append("\r\n");
                osw.write(sb.toString());
                osw.flush();
                Log.v(TAG, "服务器响应了消息" + response);
                osw.close();
                break;
            }
        } catch (IOException e) {
            Logs.d(TAG, "ex:" + e.toString());
            e.printStackTrace();
        }
    }
}
